/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86132
 * Date: 2022-03-25
 * Time: 22:14
 */
public class HashBuck {
    static class Node{
        public int val;
        public int key;
        public Node next;
        public Node(int key,int val){
            this.key=key;
            this.val=val;
        }
    }
    public Node[] array;
    public int usedSize;

    public static final double DEFAULT_LOAD_FACTOR=0.75;

    public HashBuck(){
        this.array=new Node[10];
    }

    public void put(int key,int val){
        int index=key%this.array.length;
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                cur.val=val;
                return;
            }
            cur=cur.next;
        }
        Node node=new Node(key,val);
        node.next=array[index];
        array[index]=node;
        this.usedSize++;
        if(loadFactor()>DEFAULT_LOAD_FACTOR){
            resize();
        }
    }

    private void resize(){
        Node[] newArray=new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur=array[i];
            while(cur!=null){
                int index=cur.key%newArray.length;
                Node curNext=cur.next;
                cur.next=newArray[index];
                newArray[index]=cur;
                cur=curNext;
            }
        }
        array=newArray;
    }
    private double loadFactor(){
        return 1.0*usedSize/array.length;
    }
    public int get(int key){
        int index=key%this.array.length;
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                return cur.val;
            }
            cur=cur.next;
        }
        return -1;
    }

    public static void main(String[] args) {
        HashBuck hashBuck=new HashBuck();
        hashBuck.put(1,1);
        hashBuck.put(12,12);
        hashBuck.put(3,3);
        hashBuck.put(6,6);
        hashBuck.put(7,7);
        hashBuck.put(2,2);
        hashBuck.put(11,11);
        hashBuck.put(8,8);
        System.out.println(hashBuck.get(11));
    }

}
